

package cn.shengchao.examstar.share.ohs.local.appservice;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaCodeLineColor;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.shengchao.base.utils.QRCodeUtils;
import cn.shengchao.examstar.share.acl.ports.clients.IProductClient;
import cn.shengchao.examstar.share.acl.ports.repositories.IShareLinkRepository;
import cn.shengchao.examstar.share.domain.entity.ShareLink;
import cn.shengchao.examstar.share.domain.valobj.Product;
import cn.shengchao.examstar.share.domain.valobj.SamplePoster;
import cn.shengchao.examstar.share.domain.valobj.User;
import cn.shengchao.examstar.share.ohs.local.message.ShareLinkDto;
import com.quaint.poster.core.impl.PosterDefaultImpl;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.continew.starter.cache.redisson.util.RedisUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.net.URI;
import java.util.Optional;

@Service
public class ShareAppService {

    @Autowired
    private IProductClient iproductClient;

    @Autowired
    private IShareLinkRepository iShareLinkRepository;

    @Autowired
    WxMaService wxMaService;

    public String createShareLink(ShareLinkDto shareLinkDto) {
        new ShareLink();
        Optional<ShareLink> shareLinkOptional = iShareLinkRepository.getShareLinkByProductIdAndShareUserId(shareLinkDto
                .getProductId(), shareLinkDto.getUserId());
        ShareLink shareLink = shareLinkOptional.orElse(new ShareLink());
        if (shareLink.getShareCode() != null) {
            return shareLink.getShareCode();
        }
        //分享人
        User shareUser = new User();
        //分享码
        String shareCode = RandomUtil.randomStringUpper(10);
        if (shareLinkDto.getProductId() != -1) {
            //产品
            Product product = iproductClient.getProductById(shareLinkDto.getProductId());
            shareLink.setProduct(product);

        }
        shareUser.setId(shareLinkDto.getUserId());
        shareUser.setNickName(shareLinkDto.getNickName());
        shareLink.setShareCode(shareCode);
        shareLink.setShareUser(shareUser);
        shareLink.setPath(shareLinkDto.getPath());
        shareLink.setTitle(shareLinkDto.getTitle());
        iShareLinkRepository.save(shareLink);
        return shareCode;
    }

    public String getShareQrCode(Long userId, String path, String type, String shareCode, String nickName) throws Exception {
        String code = "share_qrcode_" + userId + "_" + shareCode + "_" + type;
        String qrcodeStr = "";
        if (StrUtil.isNotBlank(qrcodeStr)) {
            return qrcodeStr;
        }
        File qrFile;
        if ("xcx".equals(type)) {
            qrFile = createQrCode(path, shareCode, nickName);
        }else {
            qrFile=QRCodeUtils.encodeToJpg(path+"?s="+shareCode);
        }
        byte[] image = mergePoster(qrFile);
        qrcodeStr = "data:image/png;base64," + Base64.encode(image);
        RedisUtils.set(code, qrcodeStr);
        return qrcodeStr;
    }

    private byte[] mergePoster(File qrcodeFile) {
        try {
            BufferedImage background = ImageIO.read(URI.create("http://exam-star.oss-cn-beijing.aliyuncs.com/2025/4/22/68076363e4b082c9d5b46096.png").toURL());
            BufferedImage qrcode = ImageIO.read(qrcodeFile);
            SamplePoster poster = SamplePoster.builder()
                    .backgroundImage(background)
                    .mainImage(qrcode)
                    .build();
            PosterDefaultImpl<SamplePoster> impl = new PosterDefaultImpl<>();
            BufferedImage posters = impl.annotationDrawPoster(poster).draw(null);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(posters, "png", outputStream);
            return outputStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

    public File createQrCode(String path, String shareCode, String nickName) throws WxErrorException {

        return wxMaService.getQrcodeService().
                createWxaCodeUnlimit("s=" + shareCode, path, false, "release", 200, false,
                        new WxMaCodeLineColor()
                        , true);
    }

    public void clickShareLink(Long userId, String shareCode) {
        Optional<ShareLink> shareLinkOptional = iShareLinkRepository.getShareLinkByShareCode(shareCode);
        ShareLink shareLink = shareLinkOptional.orElse(new ShareLink());
        if (shareLink.getShareCode() != null) {
            //自己点击自己的链接
            if (userId == shareLink.getShareUser().getId()) {
                return;
            }
            //点击人
            User clickUser = new User();
            clickUser.setId(userId);
            iShareLinkRepository.addLog(shareLink, clickUser);
        }
    }

    public Optional<ShareLink> getShareInfo(String shareCode) {
        return iShareLinkRepository.getShareLinkByShareCode(shareCode);
    }
}
